package com.cqemme.hardwareservice.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Random;

public class TimeUtil {
    /*
     * 将时间戳转换为时间模板字符串
     */
    public static String stampToDate(String s) {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long lt = Long.parseLong(s);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }

    /*
     * 将时间戳转换为时间
     */
    public static Date toDate(String s) {
        long lt = Long.parseLong(s);
        return new Date(lt);
    }

    /*
     * 将时间转换为时间戳
     */
    public static String dateToStamp(String s) throws ParseException {
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = simpleDateFormat.parse(s);
        long ts = date.getTime();
        res = String.valueOf(ts);
        return res;
    }

    /**
     * 得到今天是本周几
     *
     * @return
     */
    public static Integer getWeekday() {
        Date today = new Date();
        Calendar c = Calendar.getInstance();
        c.setTime(today);
        int weekday = c.get(Calendar.DAY_OF_WEEK) - 1;
        return weekday == 0 ? 7 : weekday;
    }

    /**
     * 获取6位随机生成的验证码
     *
     * @return
     */
    public static String getRandomCode(int n) {
        String[] verifyString = new String[]{"0", "1", "2", "3", "4", "5",
                "6", "7", "8", "9"};
        Random random = new Random(System.currentTimeMillis());
        StringBuilder verifyBuilder = new StringBuilder();
        for (int i = 0; i < n; i++) {
            int rd = random.nextInt(10);
            verifyBuilder.append(verifyString[rd]);
        }
        String verifyCode = verifyBuilder.toString();
        return verifyCode;
    }

    /**
     * 返回当前时间距离凌晨有多少秒
     *
     * @return
     */
    public static int getSecondsNextEarlyMorning() {
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DAY_OF_YEAR, 1);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.MILLISECOND, 0);
        long nowTime = System.currentTimeMillis();
        int i = (nowTime + "").length() > 10 ? 1000 : 1;
        return (int)(cal.getTimeInMillis() - nowTime) / i;
    }

    /**
     * 用于获取回复校徽流水号
     * @return
     */
    static int a=1000;
    public static  String getSerialNumber(){
        String time=stampToDate(System.currentTimeMillis() + "")
                .replace(" ","")
                .replace("-","")
                .replace(":","");
        int code=a++;
        return time+code;
    }

}
